package com.wn.service;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeRefundRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.model.result.AlipayF2FRefundResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.common.base.BaseService;
import com.common.entity.*;
import com.common.mqconfig.ExpireMessage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mq.conf.DelayQueueConfig;
import com.wn.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OrderService implements BaseService<Order> {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public PageInfo<Order> searchSomeByPage(PageParam<Order> pageParam) {
        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            List<Order> newscategoryList=orderMapper.superSearch(pageParam.getSuperSearchKeyWord());
            PageInfo<Order> newshotelPageInfo = new PageInfo<Order>(newscategoryList);
            return newshotelPageInfo;
        }else {
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for (int i = 0; i < pageParam.getOrderParams().length; i++) {
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }
            List<Order> programmes = orderMapper.searchSomeByPage(pageParam.getModel());
            PageInfo<Order> orderPageInfo = new PageInfo<Order>(programmes);
            return orderPageInfo;
        }
    }


    @Override
    public Order getOneById(String id) {
        Order oneById = orderMapper.getOneById(id);
        if (!StringUtils.isEmpty(oneById)) {
            return oneById;
        }
        return null;
    }

    @Override
    public Rsp addOne(Order order) {
        order.setId(UUID.randomUUID().toString().replace("-",""));
        int i = orderMapper.addOne(order);
        if(i>0){
            return Rsp.success(order) ;
        }
        return Rsp.fail();
    }

    @Override
    public Rsp update(Order order) {
        int i = orderMapper.update(order);
        if(i>0){
            return Rsp.success(orderMapper.getOneById(order.getId())) ;
        }
        return Rsp.fail();
    }

    @Override
    public Rsp deleteLogical(Order order) {
        order.setDeleted(Num.DELETED_TRUE);
        int i = orderMapper.update(order);
        if(i>0){
            return Rsp.success(orderMapper.getOneById(order.getId())) ;
        }
        return Rsp.fail();
    }

    //预下单
    @Transactional
    public Rsp bookingOrder(Order order) {
        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = UUID.randomUUID().toString().replaceAll("-","");

        //拿到前端的订单统一响应码，判断redis中是否存在，存在则从redis中拿到outTradeNo,返回订单详情（二维码）
        String isExis = redisTemplate.opsForValue().get(order.getOnlyCode());
        System.out.println(isExis);
        if(!StringUtils.isEmpty(isExis)){
            //创建一个新的线程，用来向支付宝查询订单的支付状态
            new Thread(new Runnable() {
                @Override
                public void run() {
                    queryOrderStatus(isExis);
                }
            }).start();
            Order orders = orderMapper.searchByorderNo(isExis);
            System.out.println("--------------");
            return Rsp.success(orders);

        }else{
            //不存在则存入redis将用统一响应码做key，生成订单编号的值做value，20分钟后自动过期
            redisTemplate.opsForValue().set(order.getOnlyCode(),outTradeNo,20*60, TimeUnit.SECONDS);
        }



        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = "飓风证照当面付扫码消费";

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = "0.01";

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        String body = "购买商品3件共20.00元";

        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");

        // 支付超时，定义为20分钟
        String timeoutExpress = "20m";

        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<>();
        // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        GoodsDetail goods1 = GoodsDetail.newInstance("goods_id001", "xxx小面包", 1000, 1);
        // 创建好一个商品后添加至商品明细列表
        goodsDetailList.add(goods1);

        // 继续创建并添加第一条商品信息，用户购买的产品为“黑人牙刷”，单价为5.00元，购买了两件
        //GoodsDetail goods2 = GoodsDetail.newInstance("goods_id002", "xxx牙刷", 500, 2);
        //goodsDetailList.add(goods2);

        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
                .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
                .setTimeoutExpress(timeoutExpress)
                //                .setNotifyUrl("http://www.test-notify-url.com")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setGoodsDetailList(goodsDetailList);
        Configs.init("zfbinfo.properties");
        AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            //test
            case SUCCESS:
                log.info("支付宝预下单成功: ");
                AlipayTradePrecreateResponse response = result.getResponse();
//                dumpResponse(response);
                //支付宝返回的二维码地址
                String qrCode = response.getQrCode();
                //创建一个新的线程，用来向支付宝查询订单的支付状态
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        queryOrderStatus(order.getOrderNo());
                    }
                }).start();
                //将二维码地址存入二维码地址
                order.setQrCode(qrCode); //order.setTotalMoney(Long.parseLong(totalAmount));
                //添加订单id
                order.setId(outTradeNo);
                //生成订单编号
                order.setOrderNo(outTradeNo);
                //订单状态0-----待支付
                order.setStatus(0);
                //添加订单
                int i = orderMapper.addOne(order);
                if(i>0){
                    return Rsp.success(order);
                }else{
                    //mq发送消息，清除redis中的唯一标识符k-v
                    rabbitTemplate.convertSendAndReceive("spring.direct.order.exchage","order.add.fail",order.getOnlyCode());
                    return Rsp.fail();
                }

            case FAILED:
//                log.error();
                System.out.println("支付宝预下单失败!!!");
                break;

            case UNKNOWN:
//                log.error();
                System.out.println("系统异常，预下单状态未知!!!");
                break;

            default:
                System.out.println("不支持的交易状态，交易返回异常!!!");
//                log.error();
                break;
        }
        return Rsp.fail();
    }

    //计时器，查询次数
    public  void queryOrderStatus(String outTradeNo) {
        final  Timer timer = new Timer();
//        final int[] count = {50};
        List<Integer> list = new ArrayList<>();
        list.add(120);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Integer n = list.get(0);
                n--;
                list.set(0,n);
                System.out.println(list.get(0));
                if(n == 0){
                    // 中断定时任务
                    timer.cancel();
                    //rabbitTemplate.convertSendAndReceive("spring.direct.order.exchage","order.add.fail","success");
                    //发送带有过期时间消息的api （延时队列的名字，消息-Object，自定义延时消息对象）
                    rabbitTemplate.convertAndSend(DelayQueueConfig.DELAY_QUEUE,(Object) outTradeNo,new ExpireMessage("10000"));
                }
                //查询订单状态
                Boolean orderStatus = test_trade_query(outTradeNo);
                if(orderStatus){
                    // 中断定时任务
                    timer.cancel();
                }
            }
        },1000,1000);
    }
    //向支付宝查询订单是否成功
    // 测试当面付2.0查询订单
    public Boolean test_trade_query(String outTradeNo) {
        // (必填) 商户订单号，通过此商户订单号查询当面付的交易状态
//        String outTradeNo = "4984da19-e48a-416d-95a0-525641fc2aa6";
        // 创建查询请求builder，设置请求参数
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder()
                .setOutTradeNo(outTradeNo);

        Configs.init("zfbinfo.properties");
        AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
        AlipayF2FQueryResult result = tradeService.queryTradeResult(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
//                log.info(: )");
                System.out.println("\"查询返回该订单支付成功");
                //修改订单状态：1----------已支付
                orderMapper.updateStatus(outTradeNo,1);
                return true;

            case FAILED:
//                log.error("查询返回该订单支付失败或被关闭!!!");
                System.out.println("查询返回该订单未支付或被关闭!!!");
                break;

            case UNKNOWN:
//                log.error();
                System.out.println("系统异常，订单支付状态未知!!!");
                break;

            default:
//                log.error();
                System.out.println("不支持的交易状态，交易返回异常!!!");
                break;
        }
        return false;
    }

    //查询订单状态根据订单号
    public Rsp queryOrderStatusFromDB(String orderNo){
        Order orders = orderMapper.searchByorderNo(orderNo);
        return Rsp.success(orders);
    }

    // 测试退款
    public Rsp test_trade_refund(Order order) {
        // (必填) 外部订单号，需要退款交易的商户外部订单号
        String outTradeNo = order.getOrderNo();
        //String outTradeNo = "tradepay14817938139942440181";

        // (必填) 退款金额，该金额必须小于等于订单的支付金额，单位为元
        String refundAmount = "0.01";

        // (可选，需要支持重复退货时必填) 商户退款请求号，相同支付宝交易号下的不同退款请求号对应同一笔交易的不同退款申请，
        // 对于相同支付宝交易号下多笔相同商户退款请求号的退款交易，支付宝只会进行一次退款
        String outRequestNo = "";

        // (必填) 退款原因，可以说明用户退款原因，方便为商家后台提供统计
        String refundReason = "正常退款，用户买多了";

        // (必填) 商户门店编号，退款情况下可以为商家后台提供退款权限判定和统计等作用，详询支付宝技术支持
        String storeId = "test_store_id";

        // 创建退款请求builder，设置请求参数
        AlipayTradeRefundRequestBuilder builder = new AlipayTradeRefundRequestBuilder()
                .setOutTradeNo(outTradeNo).setRefundAmount(refundAmount).setRefundReason(refundReason)
                .setOutRequestNo(outRequestNo).setStoreId(storeId);
        AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
        AlipayF2FRefundResult result = tradeService.tradeRefund(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("支付宝退款成功: )");
                //改变支付状态，3----------已退款
                orderMapper.updateStatus(outTradeNo,3);
                return Rsp.success(order);
            case FAILED:
                log.error("支付宝退款失败!!!");
                break;

            case UNKNOWN:
                log.error("系统异常，订单退款状态未知!!!");
                break;

            default:
                log.error("不支持的交易状态，交易返回异常!!!");
                break;
        }
        return Rsp.fail();
    }

    public Rsp updateOrderStatus(String orderNo, Integer status) {
        Order oneById = orderMapper.getOneById(orderNo);
        if(oneById.getStatus()==1){
            return Rsp.success(oneById).msg("已成功支付");
        }
        int i = orderMapper.updateStatus(orderNo, status);
        if(i>0){
            return Rsp.success(orderMapper.searchByorderNo(orderNo)).msg("修改订单状态成功");
        }
       return Rsp.fail().msg("修改订单状态失败");
    }

    public Rsp queryByCreateUserId(String createUserId) {
        List<Order> list = orderMapper.queryByCreateUserId(createUserId);
        if(StringUtils.isEmpty(list)){
            return Rsp.fail().msg("没有订单信息");
        }
        return Rsp.success(list).msg("查询订单信息成功");
    }
}
